package OSI.OSU.SI.OVI.OSI.AVI.AEI.ACI.ASI.OVI.OEI.OCI.OSI.PVI.PEI.PCI.PSI.addZNSZPage;

import ME.VPC.M.app.App;
import M_V.MVQ.button.DetaButton;
import M_V.MVQ.filenameFilter.TXTFilter;
import exception.thread.DetaThread;
import S_A.pheromone.IMV_SQI;
import U_A.PEU.P.sound.SoundRecord;
import U_A.PEU.P.wave.DFT;

import javax.imageio.ImageIO;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import java.awt.Color;
import java.awt.Container;
import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;

public class JpZNSZ extends JPanel implements Runnable {
    
    LYGFileIO lYGFileIO;
    public Thread thread;
    public DFT dFT;
    Thread time;
    public int reg = 0;
    public JpWave waveJpanel;
    int type = 0;
    SoundRecord rec;
    Vector<Line2D.Double> lines;
    Vector<Line2D.Double> forOutput;
    BufferedImage imageForOutput;
    Jpv jpv;

    //
    public JpZNSZ(Container jpanelFourth, DFT dFT, JTextPane text
        , BufferedImage imageForOutput, App NE) {
        this.imageForOutput = imageForOutput;
        this.dFT = dFT;
        forOutput = new Vector<Line2D.Double>();
        rec = new SoundRecord(null);

        double[]  fft = new double[1024];
        fft[4] = 500.0;
        LYGFileIO lYGFileIO = new LYGFileIO().initWithFFT(new double[1024], NE);
        waveJpanel = new JpWave(lYGFileIO);

        JButton jButtonStart = new DetaButton("启动", 100, 50, Color.pink);
        jButtonStart.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                reg = 1;
                type = 0;
                thread = new Thread(JpZNSZ.this);
                thread.setPriority(Thread.MIN_PRIORITY);
                thread.start();
                jpanelFourth.validate();
            }
        });
        jButtonStart.setSize(100, 30);
        jButtonStart.setBounds(500, 20, 100, 30);
        JButton jButtonStop = new DetaButton("关闭", 100, 50, Color.black);
        jButtonStop.setForeground(Color.white);
        jButtonStop.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                reg = 0;
                waveJpanel.reg = 0;
                jpanelFourth.validate();
            }
        });
        jButtonStop.setSize(100, 30);
        JButton jButtonMakesArray = new DetaButton("生成数列", 100 - 20, 50, Color.green);
        jButtonMakesArray.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                reg = 2;
                if (forOutput == null) {
                    return;
                }
                if (forOutput.size() <= 0) {
                    return;
                }
                if (text.getText().length() > 5000) {
                    return;
                }
                StringBuilder page = new StringBuilder();
                Iterator<Line2D.Double> iterator = forOutput.iterator();
                while (iterator.hasNext()) {
                    Line2D.Double setOfi = iterator.next();
                    page.append(" " + setOfi.getX2() + ":" + setOfi.getY2());
                }
                if (!text.getText().isEmpty()) {
                    text.setText(text.getText() + "\r\n\r\n" + page.toString());
                } else {
                    text.setText(page.toString());
                }
                text.validate();
            }
        });
        jButtonMakesArray.setSize(100, 30);

        JButton jButtonReadArray = new DetaButton("读取数列", 100 - 20, 50, Color.green);
        jButtonReadArray.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                reg = 2;
                if (forOutput == null) {
                    return;
                }
                if (forOutput.size() <= 0) {
                    return;
                }
                if (text.getText().length() > 5000) {
                    return;
                }
                StringBuilder page = new StringBuilder();
                Iterator<Line2D.Double> iterator = forOutput.iterator();
                while (iterator.hasNext()) {
                    Line2D.Double setOfi = iterator.next();
                    page.append(" " + setOfi.getX2() + ":" + setOfi.getY2());
                }
                if (!text.getText().isEmpty()) {
                    text.setText(text.getText() + "\r\n\r\n" + page.toString());
                } else {
                    text.setText(page.toString());
                }
                text.validate();
            }
        });
        jButtonReadArray.setSize(100, 30);

        JButton jButtonSaveImage = new DetaButton("保存图片", 100 - 20, 50, Color.magenta);
        jButtonSaveImage.addActionListener(new ActionListener() {
            @SuppressWarnings("unused")
            public void actionPerformed(ActionEvent e) {
                reg = 0;
                //锟斤拷取图片
                //锟斤拷锟斤拷锟斤拷锟斤拷锟
                if (null == imageForOutput) {
                    return;
                }
                //get path
                FileDialog filedialog = new FileDialog(new Frame(), "保存图片到..", FileDialog.LOAD);
                filedialog.setFilenameFilter(new TXTFilter("png"));
                filedialog.setVisible(true);
                String filepath = filedialog.getDirectory() + filedialog.getFile();
                S_logger.Log.logger.info("" + filepath);
                try {
                    File outputBin = new File(filepath + ".png");
                    if (null == imageForOutput) {
                        return;
                    }
                    ImageIO.write(imageForOutput, "png", outputBin);
                } catch (IOException writePngError) {
                    S_logger.Log.logger.info("" + filepath);
                }
                //锟斤拷锟酵计
            }
        });
        jButtonSaveImage.setSize(100, 30);

        JButton jButtonDetectNoise = new DetaButton("噪声检测", 100 - 20, 50, Color.black);
        jButtonDetectNoise.setForeground(Color.white);
        jButtonDetectNoise.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                reg = 1;
                type = 1;
                thread = new Thread(JpZNSZ.this);
                thread.setPriority(Thread.MIN_PRIORITY);
                thread.start();
                jpanelFourth.validate();
            }
        });
        jButtonDetectNoise.setSize(100, 30);

        JButton jButtonReadImage = new DetaButton("读取图片", 100 - 20, 50, Color.black);
        jButtonReadImage.setForeground(Color.white);
        jButtonReadImage.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                reg = 1;
                type = 1;
                thread = new Thread(JpZNSZ.this);
                thread.setPriority(Thread.MIN_PRIORITY);
                thread.start();
                jpanelFourth.validate();
            }
        });
        jButtonReadImage.setSize(100, 30);

        JButton jButtonReadImage1 = new DetaButton("调制解调", 100 - 20, 50, Color.black);
        jButtonReadImage1.setForeground(Color.white);
        jButtonReadImage1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                reg = 1;
                type = 1;
                //new fft[];
//				double[]  fft= new double[1024];
//				fft[4]= 500;
//				LYGFileIO lYGFileIO= new LYGFileIO().initWithFFT(new double[1024], makeContainerZNSZ);
//				waveJpanel= new org.LYG.node.sound.wavePlay.jp(lYGFileIO);
                waveJpanel.reg = 5;
                thread = new Thread(waveJpanel);
                thread.setPriority(Thread.MIN_PRIORITY);
                thread.start();
                ;
                jpanelFourth.validate();
            }
        });
        jButtonReadImage1.setSize(100, 30);

        DetaButton jButtonUndustMonit = new DetaButton("山林", 100 - 10, 50, Color.green);
        jButtonUndustMonit.setForeground(Color.white);
        jButtonUndustMonit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                reg = 1;
                type = 1;
                thread = new Thread(JpZNSZ.this);
                thread.setPriority(Thread.MIN_PRIORITY);
                thread.start();
                jpanelFourth.validate();
            }
        });
        jButtonUndustMonit.setSize(100, 30);

        DetaButton jButtonSeasideMonit = new DetaButton("海边", 100 - 20, 50, Color.blue);
        jButtonSeasideMonit.setForeground(Color.white);
        jButtonSeasideMonit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                reg = 1;
                type = 1;
                thread = new Thread(JpZNSZ.this);
                thread.setPriority(Thread.MIN_PRIORITY);
                thread.start();
                jpanelFourth.validate();
            }
        });
        jButtonSeasideMonit.setSize(100, 30);

        JButton jButtonImaginationMonit = new DetaButton("美梦", 100 - 20, 50, Color.magenta);
        jButtonImaginationMonit.setForeground(Color.white);
        jButtonImaginationMonit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                reg = 1;
                type = 1;
                thread = new Thread(JpZNSZ.this);
                thread.setPriority(Thread.MIN_PRIORITY);
                thread.start();
                jpanelFourth.validate();
            }
        });
        jButtonImaginationMonit.setSize(100, 30);

        JButton jButtonLibraryMonit = new DetaButton("阅读", 100 - 20, 50, Color.yellow);
        jButtonLibraryMonit.setForeground(Color.white);
        jButtonLibraryMonit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                reg = 1;
                type = 1;
                thread = new Thread(JpZNSZ.this);
                thread.setPriority(Thread.MIN_PRIORITY);
                thread.start();
                jpanelFourth.validate();
            }
        });
        jButtonLibraryMonit.setSize(100, 30);

        this.add(jButtonStart);
        this.add(jButtonStop);
        this.add(jButtonMakesArray);
        this.add(jButtonReadArray);
        this.add(jButtonSaveImage);
        this.add(jButtonReadImage);
        this.add(jButtonDetectNoise);
        this.add(jButtonReadImage1);
        this.add(jButtonUndustMonit);
        this.add(jButtonSeasideMonit);
        this.add(jButtonImaginationMonit);
        this.add(jButtonLibraryMonit);
        jpv = new Jpv(imageForOutput.getGraphics());
        jpv.setBounds(100, 0, 400, 400);
        jpv.setVisible(true);
        this.add(jpv);
    }

    @SuppressWarnings({"unchecked", "unused"})
    public void run() {
        while (reg == 1) {
            //S_logger.Log.logger.info("" + "luo");
            SoundWaveVector sw = new SoundWaveVector();
            time = new Thread(rec);
            time.setPriority(6);
            TargetDataLine line;
            AudioFormat.Encoding encoding = AudioFormat.Encoding.PCM_SIGNED;
            float rate = 19200f;
            int sampleSize = 16;
            String signedString = "signed";
            boolean bigEndian = true;
            int channels = 2;
            AudioFormat format = new AudioFormat(encoding, rate, sampleSize,
                    channels, (sampleSize / 8) * channels, rate, bigEndian);
            Map<String, String> cache_sj = new IMV_SQI();
            Map<String, String> cache_bz = new IMV_SQI();
//			//InputStream ain= getClass().getResourceAsStream("zabo.txt");
//			//DetaBufferedReader acReader= new DetaBufferedReader(DetaInputStreamReader.E(ain));  
//			//String actempString= null; 
//			try {
//				//while ((actempString= acReader.readDetaLine()) != null) {
//					//cache_bz.put(actempString, actempString);
//				//}
//				//acReader.closeDeta();
//			} catch (IOException e1) {
//	//				e1.printStackTrace();
//			}
            while (reg == 1) {
                DetaThread.sleepDeta(1);
                DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
                if (!AudioSystem.isLineSupported(info)) {
                    return;
                }
                // get and open the target data line for capture.
                try {
                    line = (TargetDataLine) AudioSystem.getLine(info);
                    line.open(format, line.getBufferSize());
                } catch (LineUnavailableException ex) {
                    return;
                } catch (SecurityException ex) {
                    //shutDown(ex.toString());
                    return;
                } catch (Exception ex) {
                    //shutDown(ex.toString());
                    return;
                }
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                DetaThread.sleepDeta(100);
                int frameSizeInBytes = format.getFrameSize();
                int bufferLengthInFrames = line.getBufferSize() / 8;
                int bufferLengthInBytes = bufferLengthInFrames * frameSizeInBytes;
                //  S_logger.Log.logger.info("" + "bufferLengthInBytes : " + bufferLengthInBytes +" **");
                byte[] data = new byte[bufferLengthInBytes];
                int numBytesRead = 0;
                line.start();
                if ((numBytesRead = line.read(data, 0, bufferLengthInBytes)) == -1) {
                    break;
                }
                out.write(data, 0, numBytesRead);
                line.stop();
                line.close();
                line = null;
                // stop and close the output stream
                try {
                    out.flush();
                    out.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                // load bytes into the audio input stream for playback
                byte[] audioBytes = out.toByteArray();
                ByteArrayInputStream bais = new ByteArrayInputStream(audioBytes);
                AudioInputStream ais = new AudioInputStream(bais, format, audioBytes.length / format.getFrameSize());
                lines = sw.getVectorLines1(this, jpv, ais, cache_bz, cache_sj, dFT, forOutput
                        , imageForOutput.getGraphics(), type);
            }
            //锟斤拷示锟斤拷锟斤拷锟
            return;
        }
    }
}
